﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel.Compiler;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;

using TextFlow.Activities;
using System.Reflection;

namespace TextFlow.Engine
{
	public class TextFlowSerializer
	{
        public static void Serialize( TextFlowWorkflow workflow, XmlWriter writer )
        {
            if ( workflow == null )
            {
                throw new ArgumentNullException( "workflow" );
            }

            if ( writer == null )
            {
                throw new ArgumentNullException( "writer" );
            }

            WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();

            serializer.Serialize( writer, workflow );
        }

        public static TextFlowWorkflow Deserialize( XmlReader reader, params Assembly[] externalAssemblies )
        {
            if ( reader == null )
            {
                throw new ArgumentNullException( "reader" );
            }

            WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();

            TypeProvider provider = new TypeProvider( null );

            provider.AddAssembly( typeof( TextFlowWorkflow ).Assembly );

            if ( externalAssemblies != null )
            {
                Array.ForEach( externalAssemblies, asm => provider.AddAssembly( asm ) );
            }

            ServiceContainer container = new ServiceContainer();

            container.AddService( typeof( ITypeProvider ), provider );

            DesignerSerializationManager mgr = new DesignerSerializationManager( container );

            using ( mgr.CreateSession() )
            {
                return serializer.Deserialize( mgr, reader ) as TextFlowWorkflow;
            }
        }
	}
}
